﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApp1
{
    /// <summary>
    /// 懒汉式单例模式
    /// </summary>
    public class Utility
    {
        private Utility() { }

        /// <summary>
        /// 声明一个已经是否声明自身类的对象
        /// </summary>
        private static volatile Utility _instance = null;

        /// <summary>
        /// 锁
        /// </summary>
        private static readonly object lockHelper = new object();

        /// <summary>
        /// 创建单实例（函数方式） 双重锁
        /// </summary>
        /// <returns></returns>
        public static Utility Instance
        {
            get
            {
                if (_instance == null)
                    lock (lockHelper)
                        _instance = _instance ?? new Utility();

                //if (_instance == null)
                //{
                //    lock (lockHelper)
                //    {
                //        if (_instance == null)
                //            _instance = new Utility();
                //    }
                //}
                return _instance;
            }
        }

        public string Test()
        {
            return "Hello World";
        }
    }

    /// <summary>
    /// 饿汉式单例模式
    /// </summary>
    public class SingletonEager
    {
        private SingletonEager()
        { }

        private static readonly SingletonEager _instance = new SingletonEager();

        public static SingletonEager Instance
        {
            get { return _instance; }
        }

        public void DoSomething()
        {
            Console.WriteLine("饿汉式单例模式.");
        }
    }

    /// <summary>
    /// 懒加载单例模式
    /// </summary>
    public sealed class SingletonByLazy
    {
        private static readonly Lazy<SingletonByLazy> _lazy = new Lazy<SingletonByLazy>(() => new SingletonByLazy());

        public static SingletonByLazy Instance
        { get { return _lazy.Value; } }

        private SingletonByLazy()
        { }

        public void DoSomething()
        {
            Console.WriteLine("懒加载单例模式.");
        }
    }
}